<?php
/**
 * 购物车信息
 * Created by PhpStorm.
 * User: Jmashimaro
 * Date: 2015/1/25
 * Time: 17:26
 */
class CartApp extends MallbaseApp {

    /**
     * 购物车列表
     */
    public function index() {
        $config = require ROOT_PATH.'/data/config.qiniu.php';
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        /* 不合法的请求 */
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }

        /* 只有是自己购物车的项目才能购买 */
        $user_id = $this->checkLogin();
        $where_user_id = $user_id ? " AND cart.user_id=" . $user_id : '';
        $cart_model = m('cart');
//        $sql = 'SELECT cart.*,s.store_name,cart.rec_id FROM '.DB_PREFIX.'cart cart LEFT JOIN '.DB_PREFIX."store s ON cart.store_id = s.store_id WHERE session_id = '".SESS_ID."' {$where_user_id}";
        $sql = 'SELECT cart.*,s.store_name,cart.rec_id FROM '.DB_PREFIX.'cart cart LEFT JOIN '.DB_PREFIX."store s ON cart.store_id = s.store_id WHERE cart.user_id={$user_id}";
        $cart_items = $cart_model->getAll($sql);
        if ($cart_items) {
            $domain = get_domain().'/';
            foreach ($cart_items as $key=>$val) {
                $val['goods_image'] = $val['goods_image'] ? $config['qiniu_url'].$val['goods_image'] : '';
                $cart_items[$key] = $val;
            }
        }

        if (!$cart_items) {
            $this->ajax_return(FLAG_ERROR, '购物车里没有商品！');
        }

        $this->ajax_return(FLAG_OK, '', $cart_items);
    }


    /**
     * 加入购物车
     * @author jiayanxiu
     * @date 2015/01/25
     */
    public function add() {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        /* 不合法的请求 */
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $spec_id = $this->get_gp('spec_id', 'P');//商品规信息格表的id
        $quantity = $this->get_gp('quantity', 'P');//购买商品的数量

        /* 是否有商品 */
        $spec_model = m('goodsspec');
        $spec_info  =  $spec_model->get(array(
            'fields'        => 'g.store_id, g.goods_id, g.goods_name, g.spec_name_1, g.spec_name_2, g.default_image, gs.spec_1, gs.spec_2, gs.stock, gs.price',
            'conditions'    => $spec_id,
            'join'          => 'belongs_to_goods',
        ));

        if (!$spec_info) {
            $this->ajax_return(FLAG_ERROR, '商品不存在！');
        }

        /* 获取当前用户的商铺id */
        $store_id = $this->visitor->get('manage_store');
        /* 如果是自己店铺的商品，则不能购买 */
        if ($store_id) {
            if ($spec_info['store_id'] == $store_id) {
                $this->ajax_return(FLAG_ERROR,'这是您自己的商品，不能进行购买！');
            }
        }

        /* 是否添加过 */
        $model_cart = m('cart');
        $item_info  = $model_cart->get("spec_id={$spec_id} AND session_id='" . SESS_ID . "'");
        if (!empty($item_info)) {
            $this->ajax_return(FLAG_ERROR, '商品已经在购物车中！');
        }

        /* 商品是否已经卖完 */
        if ($quantity > $spec_info['stock']){
            $this->ajax_return(FLAG_ERROR, '商品数量不足！');
        }

        $spec_1 = $spec_info['spec_name_1'] ? $spec_info['spec_name_1'] . ':' . $spec_info['spec_1'] : $spec_info['spec_1'];
        $spec_2 = $spec_info['spec_name_2'] ? $spec_info['spec_name_2'] . ':' . $spec_info['spec_2'] : $spec_info['spec_2'];
        $specification = $spec_1 . ' ' . $spec_2;

        /* 将商品加入购物车 */
        $cart_item = array(
            'user_id'       => $this->checkLogin(),
            'session_id'    => SESS_ID,
            'store_id'      => $spec_info['store_id'],
            'spec_id'       => $spec_id,
            'goods_id'      => $spec_info['goods_id'],
            'goods_name'    => addslashes($spec_info['goods_name']),
            'specification' => addslashes(trim($specification)),
            'price'         => $spec_info['price'],
            'quantity'      => $quantity,
            'goods_image'   => addslashes($spec_info['default_image']),
        );

        /* 添加并返回购物车统计即可 */
        $cart_model =  m('cart');
        $cart_model->add($cart_item);
        $cart_status = $this->get_cart_status();

        /* 更新被添加进购物车的次数 */
        $model_goodsstatistics = m('goodsstatistics');
        $model_goodsstatistics->edit($spec_info['goods_id'], 'carts=carts+1');

        //@todo 是否要返回
        $this->ajax_return(FLAG_OK, '加入购物车成功！', $cart_status);
    }

    /**
     * 更新购物车中的商品
     * @author jiayanxiu
     * @date 2015/02/02
     */
    public function update() {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        /* 不合法的请求 */
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $spec_id = $this->get_gp('spec_id', 'P');
        $quantity = $this->get_gp('quantity', 'P');
        $spec_id  = $spec_id ? intval($spec_id) : 0;
        $quantity = $quantity ? intval($quantity): 0;

        if (!$spec_id || !$quantity){
            $this->ajax_return(FLAG_ERROR, '非法的参数！');
        }

        /* 判断库存是否足够 */
        $model_spec = m('goodsspec');
        $spec_info  =  $model_spec->get($spec_id);
        if (!$spec_info) {
            $this->ajax_return(FLAG_ERROR, '没有此商品的规格！');
        }
        /* 数量有限 */
        if ($quantity > $spec_info['stock']) {
            $this->ajax_return(FLAG_ERROR, '没有充足的货源！');
        }

        /* 修改数量 */
        $where = "spec_id={$spec_id} AND session_id='" . SESS_ID . "'";
        $model_cart =& m('cart');

        /* 获取购物车中的信息，用于获取价格并计算小计 */
        $cart_spec_info = $model_cart->get($where);
        /* 并没有添加该商品到购物车 */
        if (!$cart_spec_info) {
            $this->ajax_return(FLAG_ERROR, '并没有添加该商品到购物车！');
        }

        $store_id = $cart_spec_info['store_id'];

        /* 修改数量 */
        $model_cart->edit($where, array(
            'quantity'  =>  $quantity,
        ));

        /* 修改数量 */
        $model_cart->edit($where, array(
            'quantity'  =>  $quantity,
        ));

        /* 返回JSON结果 */
        $cart_status = $this->get_cart_status();

        /* 小计 */
        $cart_status['status']['subtotal']   =   $quantity * $cart_spec_info['price'];//小计
        $cart_status['status']['amount'] = $cart_status['carts'][$store_id]['amount'];//店铺购物车总计

        $this->ajax_return(FLAG_OK, '', $cart_status['status']);

    }

    /**
     * 删除购物车中的商品
     * @author jiayanxiu
     * @date 2015/02/02
     */
    public function drop() {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        /* 不合法的请求 */
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $rec_id = $this->get_gp('rec_id', 'P');
        $user_id = $this->checkLogin();
        if(!$user_id){
            $this->ajax_return(FLAG_ERROR ,'请您登陆！');
        }
        $model_cart = m('cart');
        $cart_goods =  $model_cart->find(array(
            'conditions'    => "rec_id ={$rec_id} AND user_id={$user_id}"
        ));
        if (!$cart_goods) {
            $this->ajax_return(FLAG_ERROR, '购物车没有该商品');
        }
        /* 从购物车中删除 */
        $droped_rows = $model_cart->drop("rec_id= {$rec_id} AND user_id= {$user_id}", 'store_id');

        if (!$droped_rows) {
            $this->ajax_return(FLAG_ERROR, '删除购物车商品失败！');
        }

        /* 返回结果 */
        $dropped_data = $model_cart->getDroppedData();//获取时时保存的已删除记录
        $cart_status = $this->get_cart_status();
        $this->ajax_return(FLAG_OK, '操作成功！', $cart_status);

    }

    /**
     * 获取购物车状态
     * @author Garbin
     * @return array
     */
    private function get_cart_status()
    {
        /* 默认的返回格式 */
        $data = array(
            'status'    =>  array(
                'quantity'  =>  0,      //总数量
                'amount'    =>  0,      //总金额
                'kinds'     =>  0,      //总种类
            ),
            'carts'     =>  array(),    //购物车列表，包含每个购物车的状态
        );

        /* 获取所有购物车 */
        $carts = $this->get_carts();
        if (empty($carts))
        {
            return $data;
        }
        $data['carts']  =   $carts;
        foreach ($carts as $store_id => $cart)
        {
            $data['status']['quantity'] += $cart['quantity'];
            $data['status']['amount']   += $cart['amount'];
            $data['status']['kinds']    += $cart['kinds'];
        }

        return $data;
    }

    /**
     * 以购物车为单位获取购物车列表及商品项
     * @author    Garbin
     * @return    void
     */
    private function get_carts($store_id = 0)
    {
        $carts = array();

        /* 获取所有购物车中的内容 */
        $where_store_id = $store_id ? ' AND cart.store_id=' . $store_id : '';

        /* 只有是自己购物车的项目才能购买 */
        $where_user_id = $this->visitor->get('user_id') ? " AND cart.user_id=" . $this->visitor->get('user_id') : '';
        $cart_model =& m('cart');
        $cart_items = $cart_model->find(array(
            'conditions'    => 'session_id = \'' . SESS_ID . "'" . $where_store_id . $where_user_id,
            'fields'        => 'this.*,store.store_name',
            'join'          => 'belongs_to_store',
        ));
        if (!$cart_items) {
            return $carts;
        }
        $kinds = array();
        foreach ($cart_items as $item)
        {
            /* 小计 */
            $item['subtotal']   = $item['price'] * $item['quantity'];
            $kinds[$item['store_id']][$item['goods_id']] = 1;

            /* 以店铺ID为索引 */
            empty($item['goods_image']) && $item['goods_image'] = Conf::get('default_goods_image');
            $carts[$item['store_id']]['store_name'] = $item['store_name'];
            $carts[$item['store_id']]['amount']     += $item['subtotal'];   //各店铺的总金额
            $carts[$item['store_id']]['quantity']   += $item['quantity'];   //各店铺的总数量
            $carts[$item['store_id']]['goods'][]    = $item;
        }

        foreach ($carts as $_store_id => $cart)
        {
            $carts[$_store_id]['kinds'] =   count(array_keys($kinds[$_store_id]));  //各店铺的商品种类数
        }

        return $carts;
    }


}